import plugin from '../../../lib/plugins/plugin.js'
import FormData from 'form-data'
import moment from 'moment'
import axios from 'axios'
import fs from 'fs'

const domain = 'h.winterqkl.cn/egg';

export class EggPlugin extends plugin {
    constructor() {
        super({
            name: '一键地球',
            dsc: '一键地球',
            event: 'message',
            priority: 1145,
            rule: [
                {
                    reg: /^(#|\/)?一键(地球|涩批|柴郡|柴郡猫)$/,
                    fnc: 'egg'
                },
                {
                    reg: /^(#|\/)?一键(.*)?/,
                    fnc: 'eggs'
                },
                {
                    reg: /^(#|\/)?来点(球图|涩批|魔法)$/,
                    fnc: 'allegg'
                }
            ]
        })
    }

    async egg(e) {
        const match = e.msg.match(/^(#|\/)?一键(地球|涩批|柴郡|柴郡猫)$/);
        if (!match) return false;
        const keyword = match[2];
        const { image, isGif } = await getimg(e);
        await this.reply('图片保存成功，正在处理，请稍等一下~', true);
        let data = null
        try {
            const imageUrlEncoded = encodeURIComponent(image);
            let Url = `https://${domain}/process-image?imageUrl=`
            if (isGif) {
                Url = `https://${domain}/processGif?gifUrl=`;
            }
            switch (keyword) {
                case '地球':
                case '涩批':
                    Url += `${imageUrlEncoded}&replacementImageUrl=replace`;
                    break;
                case '柴郡':
                case '柴郡猫':
                    Url += `${imageUrlEncoded}&replacementImageUrl=https://gitee.com/fantasy-hx/egg-plugin/raw/master/img/chaijun.png`;
                    break;
                default:
                    Url += `${imageUrlEncoded}&replacementImageUrl=replace`;
                    break;
            }
            const response = await axios({
                method: 'get',
                url: Url,
                responseType: 'arraybuffer'
            });
            const responseData = response.data;
            await this.reply([segment.image(responseData)], true);
            data = responseData
        } catch (error) {
            console.error('下载图片出错:', error);
            await this.reply('处理错误（未识别到人脸，或其他错误），请稍后再试', true);
        }
        if (data != null && (keyword === '地球' || keyword === '涩批')) {
            try {
                let time = moment(Date.now()).format('YYYY-MM-DD-HH:mm:ss');
                let name = `Time=${time}&Bot=${e.self_id || e.bot.uin}&User=${e.user_id}`;
                const formData = new FormData();
                formData.append('name', name);
                formData.append('img', data);
                const uploadUrl = 'https://h.winterqkl.cn/API/egg_up.php';
                const postResponse = await axios.post(uploadUrl, formData, {
                    headers: formData.getHeaders()
                });
                console.log('上传成功：', postResponse.data);
            } catch (err) {
                console.log('上传失败：', err);
            }
        }
        return true;
    }

    async eggs(e) {
        let ngm = e.msg.match(/地球|涩批|柴郡|柴郡猫/)
        if (ngm) return true
        const { image, isGif } = await getimg(e);
        let userurl
        const nickname = e.msg.replace(/一键|#/gi, '').trim()
        let qq = getKey(nickname)
        if (qq) {
            userurl = `http://q1.qlogo.cn/g?b=qq&nk=${qq}&s=100`
        } else {
            if (e.at) {
                const atid = e.at
                let aturl = `http://q1.qlogo.cn/g?b=qq&nk=${atid}&s=100`
                userurl = aturl
            } else {
                return
            }
        }
        await this.reply('图片保存成功，正在处理，请稍等一下~')
        try {
            let Url = `https://${domain}/process-image?imageUrl=`
            if (isGif) {
                Url = `https://${domain}/processGif?gifUrl=`;
            }
            const userUrlEncoded = encodeURIComponent(userurl);
            const imageUrlEncoded = encodeURIComponent(image);
            const response = await axios({
                method: 'get',
                url: `${Url}${imageUrlEncoded}&replacementImageUrl=${userUrlEncoded}`,
                responseType: 'arraybuffer'
            });
            const responseData = response.data;
            await this.reply([segment.image(responseData)])
        } catch (error) {
            console.error('下载图片出错:', error);
            await this.reply('处理错误（未识别到人脸，或其他错误），请稍后再试');
        }
        return true
    }

    async allegg(e) {
        return await this.reply(segment.image('https://h.winterqkl.cn/API/egg.php'), true)
    }
}

function getKey(value) {
    const qqpath = './plugins/egg-plugin/qq.json'
    const data = JSON.parse(fs.readFileSync(qqpath))
    for (let key in data) {
        if (Object.prototype.hasOwnProperty.call(data, key)) {
            if (data[key].includes(value)) {
                return key
            }
        }
    }
    return false
}

async function getimg(e) {
    let z = `3065737952`
    let image
    let img
    let isGif = false; // 新增变量用于判断是否为 GIF
    const re = await e.reply_id || e.source

    if (e.img) {
        img = e.img[0];
    } else {
        if (e.atBot && !re) {
            img = e.bot.avatar || `https://q1.qlogo.cn/g?b=qq&s=0&nk=${Bot.uin}`;
        } else if (e.at && !re) {
            if (e.runtime.cfg.masterQQ.includes(e.at)) {
                try {
                    img = e.group.pickMember(z).getAvatarUrl();
                } catch (error) {
                    img = `https://q1.qlogo.cn/g?b=qq&s=0&nk=${z}`;
                }
            } else {
                try {
                    img = e.group.pickMember(e.at).getAvatarUrl();
                } catch (error) {
                    img = `https://q1.qlogo.cn/g?b=qq&s=0&nk=${e.at}`;
                }
            }
        }
    }

    if (re) {
        let reply
        if (e.source) {
            if (e.isGroup) reply = (await e.group.getChatHistory(e.source.seq, 1)).pop() ?.message
            else reply = (await e.friend.getChatHistory(e.source.time, 1)).pop() ?.message
            if (reply) {
                for (const val of reply) {
                    if (val.type == "image") {
                        img = val.url
                        break
                    }
                }
            }
        }
        else if (e.reply_id) {
            let reply = (await e.getReply(e.reply_id)).message;
            for (const val of reply) {
                if (val.type === "image") {
                    img = [val.url];
                    break;
                }
            }
        }
        else {
            if (e.isGroup) reply = (await e.group.getChatHistory(re)).pop() ?.message
            else reply = (await e.friend.getChatHistory(re)).pop() ?.message
            if (reply) {
                for (const val of reply) {
                    if (val.type == "image") {
                        img = val.url
                        break
                    }
                }
            }
        }

    }
    if (img) {
        image = img;
        // 检查图片 MIME 类型
        try {
            const response = await axios({
                method: 'get',
                url: image,
                responseType: 'arraybuffer'
            })
            const contentType = response.headers['content-type'];
            isGif = contentType === 'image/gif'; // 判断是否为 GIF
        } catch (error) {
            console.error('获取图片头信息失败:', error);
        }

    }

    return { image, isGif }; // 返回对象，包含 image 和 isGif
}

